import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { isArray } from 'class-validator';
import { Observable, map } from 'rxjs';
import { ResponseDto } from '../../common/class/res.class';

export interface Response<T> {
  data: T;
}

@Injectable()
export class HttpReqTransformInterceptor<T>
  implements NestInterceptor<T, Response<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<Response<T>> {
    return next.handle().pipe(
      map((data) => {
        if (isArray(data)) {
          return new ResponseDto({ data: data });
        }
        if (data) {
          const res = data?.hasOwnProperty('data') ? { ...data } : data;
          return new ResponseDto(res);
        }
        return new ResponseDto({ ...data });
      }),
    );
  }
}
